package com.example.demo31;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;

public class RegisterActivity extends AppCompatActivity {

    private TextInputEditText etUsername, etPassword, etConfirmPassword, etEmail;
    private RadioGroup rgGender;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        // 初始化视图
        initViews();

        // 设置注册按钮点击事件
        findViewById(R.id.btnRegister).setOnClickListener(v -> validateAndRegister());
    }

    private void initViews() {
        etUsername = findViewById(R.id.etUsername);
        etPassword = findViewById(R.id.etPassword);
        etConfirmPassword = findViewById(R.id.etConfirmPassword);
        etEmail = findViewById(R.id.etEmail);
        rgGender = findViewById(R.id.rgGender);
    }

    private void validateAndRegister() {
        // 获取输入值
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        String confirmPassword = etConfirmPassword.getText().toString().trim();
        String email = etEmail.getText().toString().trim();
        String gender = getSelectedGender();

        // 验证输入
        if (!validateInput(username, password, confirmPassword, email)) {
            return;
        }

        // 保存用户数据
        saveUserData(username, password, email, gender);

        // 显示成功提示
        Toast.makeText(this, "注册成功！", Toast.LENGTH_SHORT).show();

        // 返回登录页面
        navigateToLogin();
    }

    private boolean validateInput(String username, String password,
                                  String confirmPassword, String email) {
        // 用户名验证
        if (username.isEmpty()) {
            showError(etUsername, "用户名不能为空");
            return false;
        }

        // 密码验证
        if (password.isEmpty()) {
            showError(etPassword, "密码不能为空");
            return false;
        }

        if (password.length() < 6) {
            showError(etPassword, "密码至少需要6位");
            return false;
        }

        // 确认密码验证
        if (!password.equals(confirmPassword)) {
            showError(etConfirmPassword, "两次输入的密码不一致");
            return false;
        }

        // 邮箱验证
        if (email.isEmpty() || !Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            showError(etEmail, "请输入有效的邮箱地址");
            return false;
        }

        return true;
    }

    private String getSelectedGender() {
        int selectedId = rgGender.getCheckedRadioButtonId();
        if (selectedId == R.id.rbMale) {
            return "男";
        } else if (selectedId == R.id.rbFemale) {
            return "女";
        }
        return "未选择";
    }

    private void showError(TextInputEditText editText, String error) {
        TextInputLayout layout = (TextInputLayout) editText.getParent();
        layout.setError(error);
        editText.requestFocus();
    }

    private void saveUserData(String username, String password,
                              String email, String gender) {
        SharedPreferences preferences = getSharedPreferences("UserData", MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();

        editor.putString("username", username);
        editor.putString("password", password); // 实际项目请加密存储
        editor.putString("email", email);
        editor.putString("gender", gender);
        editor.apply();
    }

    private void navigateToLogin() {
        // 示例：跳转到登录页面
        startActivity(new Intent(this, MainActivity.class));
        finish(); // 关闭当前注册页面
    }

    public void showDialog(View view)
    {
        AlertDialog alertDialog =  new AlertDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("确定要退出吗？")
                .setNegativeButton("取消",null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // finish();// 退出当前Activity
                        // 可选：完全结束应用进程（根据需求选择）
                        // System.exit(0);
                    }
                })
                .create();
        alertDialog.show();
    }
}